package www_api

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/model/system/system_modules"
	"gitee.com/theegg/go-brick/app/model/user/users"
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/gin-gonic/gin"
)

// 登陆
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if !users.HasUserFromName(username) {
		app.NewResponse(c).JsonReturn(false, "登陆失败, 请检查用户名或者密码(0x001)!", nil)
		return
	}

	user, err := users.UserLogin(username, password, c.ClientIP())
	if err != nil {
		fmt.Println(err)
		app.NewResponse(c).JsonReturn(false, "登陆失败, 请检查用户名或者密码!", nil)
		return
	}

	// 生成token
	token, errToken := user.GenToken()
	if errToken != nil {
		app.NewResponse(c).JsonReturn(false, errToken.Error(), nil)
		return
	}

	data := make(map[string]interface{})
	data["token"] = token
	data["username"] = user.Username

	app.NewResponse(c).JsonReturn(true, "登陆成功!", data)
	return
}

// 首页配置
func ConfigHome(c *gin.Context) {
	returnData := make(map[string]interface{})
	carouselData, err := system_modules.GetModuleConfig("index_carousel")
	if err != nil {
		app.NewResponse(c).JsonReturn(false, err.Error(), nil)
		return
	}

	returnData["index_carousel"] = carouselData
	app.NewResponse(c).JsonReturn(true, "获取数据成功!", returnData)
	return
}

// 登出
func Logout(c *gin.Context) {
	app.NewResponse(c).JsonReturn(true, "登出成功!", nil)
	return
}
